
<template>
  <div class="chart-card">
    <h3>资产位置统计</h3>
    <div class="chart-container">
      <!-- 环形图 -->
      <div ref="chartRef" class="chart"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import * as echarts from "echarts";
import { getAssetLocationData } from "@/api/Chart";

const chartRef = ref(null);
let chartInstance: echarts.ECharts | null = null;

onMounted(async () => {
  try {
    const res = await getAssetLocationData();
    const formattedData = res.data.map(item => ({
      name: item.locationName,
      value: Number(item.count), // 将字符串转为数值
    }));

    if (chartRef.value) {
      chartInstance = echarts.init(chartRef.value);

      const option = {
        tooltip: {
          trigger: "axis", // 轴提示
          formatter: "{b}: {c} 台", // 提示格式
        },
        xAxis: {
          type: "category",
          data: formattedData.map(item => item.name),
          axisLabel: {
            rotate: 45, // 倾斜 x 轴标签防止重叠
          },
        },
        yAxis: {
          type: "value",
          name: "资产数量（台）",
        },
        series: [
          {
            name: "资产数量",
            type: "bar",
            data: formattedData.map(item => item.value),
            label: {
              show: true,
              position: "top",
              color: "#333",
            },
            itemStyle: {
              borderRadius: 4,
              color: "#5470C6",
            },
            showBackground: true,
            backgroundStyle: {
              color: "rgba(180, 180, 180, 0.2)",
            },
          },
        ],
      };

      chartInstance.setOption(option);
    }
  } catch (error) {
    console.error("获取数据失败:", error);
  }
});
</script>

<style scoped>
.chart-card {
  width: 100%;
  max-width: 680px;
  padding: 10px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin: 15px auto;
}

.chart-card h3 {
  font-size: 18px;
  font-weight: bold;
  padding-left: 16px;
  text-align: left;
}

.chart-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.chart {
  width: 100%;
  height: 520px;
}
</style>

